<template>
	<div v-if="isAuth(['ROOT', 'APP_USER:SELECT'])">


		<!-- 搜索栏 -->


		<!-- 前端验证，自定义的验证规则dataRule -->
		<el-form :inline="true" :model="dataForm" :rules="dataRule" ref="dataForm">
		<!-- <el-form :inline="true" :model="dataForm"> -->

			<!-- prop="name"：name为dataRule这个大规则中的小规则 -->
			<!-- v-model="dataForm.name"：这里填写姓名，保存在模型层dataForm里面的name属性中 -->
			<el-form-item prop="username">
				<el-input v-model="dataForm.username" placeholder="用户名" size="large" class="input"
					clearable="clearable" />
			</el-form-item>
			<el-form-item prop="name">
				<el-input v-model="dataForm.name" placeholder="姓名" size="large" class="input" clearable="clearable" />
			</el-form-item>
			<el-form-item prop="phone">
				<el-input v-model="dataForm.phone" placeholder="手机号" size="large" class="input"
					clearable="clearable" />
			</el-form-item>
			<el-form-item prop="email">
				<el-input v-model="dataForm.email" placeholder="邮箱" size="large" class="input" clearable="clearable" />
			</el-form-item>

			<el-form-item>
				<!-- 查询的时候，要进行回调函数searchHandle()，在下面自定义 -->
				<el-button size="large" type="primary" @click="searchHandle()">查询</el-button>
				<el-button size="large" type="primary" :disabled="!isAuth(['ROOT', 'APP_USER:INSERT'])"
					@click="addHandle()">
					新增
				</el-button>
				<el-button size="large" type="danger" :disabled="!isAuth(['ROOT', 'APP_USER:DELETE'])"
					@click="deleteHandle()">
					批量删除
				</el-button>
			</el-form-item>
			<div style="float: right">
				<!-- 切换状态的时候也要调用searchHandle()回调函数 -->
				<el-radio-group v-model="dataForm.status" @change="searchHandle()">
					<el-radio-button label="有效" />
					<el-radio-button label="无效" />
				</el-radio-group>
			</div>
		</el-form>






		<!-- 表格 -->


		<!-- @sort-change="orderHandle"：当我们切换排序规则时回调函数 -->
		<!-- v-loading="dataListLoading"：是否出现加载 -->
		<!-- :row-key="getRowKeys"：getRowKeys()函数，规定用这行用户记录的主键值row.id作为表格中该行的特征标志 -->
		<!-- :expand-row-keys="expands"：expands:[]，存放要展开的行的用户的主键值row.id -->
		<!-- @expand-change="expand"：expand()回调函数，当表格展开或折叠都会调用 -->
		<el-table :data="dataList" border v-loading="dataListLoading" :cell-style="{ padding: '3px 0' }"
			style="width: 100%;" size="large" @selection-change="selectionChangeHandle" @expand-change="expand"
			:row-key="getRowKeys" :expand-row-keys="expands" @sort-change="orderHandle">
			<!-- 折叠面板功能 -->
			<el-table-column type="expand">
				<template #default="scope">
					<div>
						<table class="content">
							<tr>
								<th width="140">身高</th>
								<td width="320">{{ content.height }}</td>
								<th width="140">体重</th>
								<td width="320">{{ content.weight }}</td>
								<td width="110" rowspan="3" align="center">
									<el-upload class="avatar-uploader" :action="action" :headers="{ token: token }"
										with-credentials="true" :on-success="updateAvatarSuccess"
										:on-error="updateAvatarError" :show-file-list="false"
										:data="{ id: scope.row.id }">
										<el-image style="width: 100px; height: 100px" :src="content.avatar" :fit="fit">
											<template #error>
												<div class="error-img">
													<el-icon>
														<Picture />
													</el-icon>
												</div>
											</template>
										</el-image>
									</el-upload>
								</td>
							</tr>
							<tr>
								<th>BMI</th>
								<td>{{ content.bmi }}</td>
								<th>地址</th>
								<td>{{ content.address }}</td>
							</tr>
							<tr>
								<th>短期目标</th>
								<td>{{ content.shortTermGoal }}</td>
								<th>疾病</th>
								<td>{{ content.diseases }}</td>
							</tr>
							<tr>
								<th>偏好</th>
								<td>
									<el-tag v-for="one of content.likes">{{ one }}</el-tag>
								</td>
								<th>忌口</th>
								<td colspan="2">
									<el-tag v-for="one of content.dislikes">{{ one }}</el-tag>
								</td>
							</tr>
							<!-- <tr>
								<th>介绍信息</th>
								<td colspan="4">{{ content.description }}</td>
							</tr> -->
						</table>
					</div>
				</template>
			</el-table-column>
			<!-- 复选框列 -->
			<el-table-column type="selection" header-align="center" align="center" width="50" />
			<!-- 行号列，不是主键值 -->
			<el-table-column type="index" header-align="center" align="center" width="100" label="序号">
				<template #default="scope">
					<!-- 当前页的起始位置 + 当前这条记录在这一页中处于第几行-->
					<span>{{ (pageIndex - 1) * pageSize + scope.$index + 1 }}</span>
				</template>
			</el-table-column>
			<!-- prop="name"：后端返回给前端的json中的name属性 -->
			<el-table-column prop="username" header-align="center" align="center" min-width="120" label="用户名"
				:show-overflow-tooltip="true" />
			<el-table-column prop="name" header-align="center" align="center" min-width="120" label="姓名"
				:show-overflow-tooltip="true" />
			<el-table-column prop="sex" header-align="center" align="center" min-width="70" label="性别" />
			<el-table-column prop="birthday" header-align="center" align="center" min-width="70" label="出生日期" />
			<el-table-column prop="phone" header-align="center" align="center" min-width="120" label="手机号" />
			<el-table-column prop="email" header-align="center" align="center" min-width="100" label="邮箱" />
			<el-table-column prop="status" header-align="center" align="center" min-width="80" label="状态" />
			<el-table-column header-align="center" align="center" width="150" label="操作">
				<template #default="scope">
					<el-button link type="primary" size="large" :disabled="!isAuth(['ROOT', 'APP_USER:UPDATE'])"
						@click="updateHandle(scope.row.id)">
						修改
					</el-button>
					<el-button link type="primary" size="large" :disabled="!isAuth(['ROOT', 'APP_USER:DELETE'])"
						@click="deleteHandle(scope.row.id)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>




		<!-- 分页 -->


		<!-- @size-change="sizeChangeHandle"：改变每页记录条数触发回调函数 -->
		<!-- @current-change="currentChangeHandle"：改变当前页触发回调函数 -->
		<el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
			:page-sizes="[10, 20, 50]" :page-size="pageSize" :total="totalCount"
			layout="total, sizes, prev, pager, next, jumper"></el-pagination>
			
			
		<!-- 新增或编辑弹窗 -->
		<!-- 弹窗页面提交Ajax请求的最后，触发了refreshDataList自定义事件，该事件在app_user.vue页面里捕获，调用封装函数刷新页面的数据 -->
		<add-or-update ref="addOrUpdate" @refreshDataList="loadDataList"></add-or-update>
	</div>
</template>

<script>
	import AddOrUpdate from './app_user-add-or-update.vue';
	export default {
		components: {
			AddOrUpdate
		},
		data() {
			return {
				// 上传照片时需要用到token
				token: localStorage.getItem('token'),
				action: `${this.$baseUrl}/app_user/updateAvatar`,
				// 查询条件
				dataForm: {
					username: '',
					name: '',
					phone: '',
					email: '',
					status: '有效',
					order: null
				},
				// 查询结果
				dataList: [],
				// 分页有关变量
				pageIndex: 1,
				pageSize: 10,
				totalCount: 0,
				// 查询时是否出现加载状态
				dataListLoading: false,
				// 复选框选中的数据
				dataListSelections: [],
				// 验证规则
				dataRule: {
					username: [{
						required: false,
						pattern: '^[a-zA-Z0-9]{5,50}$',
						message: '用户名格式错误'
					}],
					name: [{
						required: false,
						pattern: '^[\u4e00-\u9fa5]{1,20}$',
						message: '姓名格式错误'
					}],
					phone: [{
						required: false,
						pattern: '^1[3-9]\d{9}$',
						message: '手机号格式错误'
					}],
					email: [{
						required: false,
						pattern: '^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$',
						message: '邮箱格式错误'
					}]
				},
				// 展开的行
				expands: [],
				// 规定用这行用户记录的主键值row.id作为表格中该行的特征标志
				getRowKeys(row) {
					return row.id;
				},
				content: {
					id: null,
					height: '',
					weight: '',
					avatar: '',
					bmi: '',
					address: '',
					shortTermGoal: '',
					diseases: '',
					likes: '',
					dislikes: ''
				}
			};
		},
		methods: {
			// 查询分页记录
			loadDataList: function() {
				let that = this;
				that.dataListLoading = true;
				let json = {
					有效: 1,
					无效: 0
				};
				let data = {
					page: that.pageIndex,
					length: that.pageSize,
					username: that.dataForm.username == '' ? null : that.dataForm.username,
					name: that.dataForm.name == '' ? null : that.dataForm.name,
					phone: that.dataForm.phone == '' ? null : that.dataForm.phone,
					email: that.dataForm.email == '' ? null : that.dataForm.email,
					status: json[that.dataForm.status],
					order: that.dataForm.order
				};
				console.log(data);
				that.$http('/app_user/searchByPage', 'POST', data, true, function(resp) {
					let result = resp.result;
					let temp = {
						'1': '有效',
						'0': '无效'
					};
					for (let one of result.list) {
						one.status = temp[one.status + ''];
					}
					that.dataList = result.list;
					that.totalCount = result.totalCount;
					that.dataListLoading = false;
				});
			},

			// 分页组件回调函数
			sizeChangeHandle: function(val) {
				this.pageSize = val;
				this.pageIndex = 1;
				this.loadDataList();
			},
			currentChangeHandle: function(val) {
				this.pageIndex = val;
				this.loadDataList();
			},

			// 实现条件查询
			searchHandle: function() {
				let that = this;
				that.$refs['dataForm'].validate(valid => {
					if (valid) {
						// 将页面中之前的验证提示清空
						that.$refs['dataForm'].clearValidate();
						if (that.pageIndex != 1) {
							that.pageIndex = 1;
						}
						that.loadDataList();
					} else {
						return false;
					}
				});
			},

			// 实现列排序
			orderHandle: function(param) {
				let prop = param.prop;
				let order = param.order;
				if (order == 'ascending') {
					this.dataForm.order = 'ASC';
				} else if (order == 'descending') {
					this.dataForm.order = 'DESC';
				} else {
					return;
				}
				this.dataList = [];
				this.loadDataList();
			},
			
			// 展开或折叠行
			// row：当前行的记录
			// expandedRows：当前展开的行的记录
			expand: function(row, expandedRows) {
				let that = this;
				if (expandedRows.length > 0) {
					// 只能展开一行
					that.expands = [];
					that.expands.push(row.id);
					let json = {
						有效: 1,
						无效: 0
					};
					let data = {
						id: row.id,
						status: json[row.status]
					};
					console.log("data");
					console.log(data);
					// 走同步ajax请求
					that.$http('/app_user/searchById', 'POST', data, false, function(resp) {
						console.log(resp);
						// that.content = resp.result;
						that.content.id = row.id;
						that.content.height = resp.height;
						that.content.weight = resp.weight;
						that.content.bmi = resp.bmi;
						that.content.address = resp.address;
						that.content.shortTermGoal = resp.short_term_goal;
						that.content.diseases = resp.diseases;
						that.content.likes = resp.likes;
						that.content.dislikes = resp.dislikes;
						// js中模板字符串的使用
						// ${that.$minioUrl}：minio服务器地址
						// ${resp.avatar}：图片的相对路径，在哪个存储桶下
						// random=${Math.random()}：防止浏览器缓存
						that.content.avatar = `${that.$minioUrl}${resp.avatar}?random=${Math.random()}`;
					});
					console.log(that.content);
				} else {
					that.expands = [];
				}
			},
			
			// 上传头像成功
			updateAvatarSuccess: function() {
				this.content.avatar = `${this.$minioUrl}/shanyi-mis/avatar/app-user-${this.content.id}.jpg?random=${Math.random()}`;
			},
			
			// 上传头像失败
			updateAvatarError: function() {
				ElMessage({
					message: '头像上传失败',
					type: 'error',
					duration: 1200
				});
			},
			
			// 新增按钮点击事件
			addHandle: function() {
				// 使用$nextTick函数可以保证init函数中的代码都能执行完，不会强制结束
				this.$nextTick(() => {
					// 调用app_user-add-or-update.vue组件中的init函数
					this.$refs.addOrUpdate.init();
				});
			},
			
			// 修改按钮点击事件
			updateHandle: function(id) {
				this.$nextTick(() => {
					this.$refs.addOrUpdate.init(id);
				});
			},
			
			// 复选框选中的数据更改
			selectionChangeHandle: function(val) {
				this.dataListSelections = val;
				console.log(this.dataListSelections);
			},
			
			// 批量删除或单个删除
			deleteHandle: function(id) {
				let that = this;
				let ids = id ? [id] : that.dataListSelections.map(one => { return one.id });
				if (ids.length == 0) {
					ElMessage({
						message: '没有选中的记录',
						type: 'warning',
						duration: 1200
					});
				} else {
					ElMessageBox.confirm('确定删除选中的记录吗?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						let data = {
							ids: ids
						};
						that.$http('/app_user/deleteAppUser', 'POST', data, true, function(resp) {
							ElMessage({
								message: '删除成功',
								type: 'success',
								duration: 1200,
								onClose: () => {
									that.loadDataList();
								}
							});
						});
					}).catch(() => {
						ElMessage({
							type: 'info',
							message: '已取消删除'
						});
					});
				}
			}

		},
		// 页面加载时调用
		created: function() {
			this.loadDataList();
		},
		
	};
</script>

<style lang="less" scoped="scoped">
	@import url(app_user.less);
</style>